package com.talent.jiwen.teacher;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.adapter.CourseWaitAdapter;
import com.talent.jiwen.base.BaseFragment;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.OrderResult;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

public class CourseWaitListFragment extends BaseFragment {
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;

    List<OrderResult.Order> courseList = new ArrayList<>();
    private CourseWaitAdapter courseWaitAdapter;
    private Handler handler;
    private TimeRunnable timeRunnable;
    private Thread timeThread;

    public static final String REFRESH_COURSE_WAIT_LIST = "refresh.course.wait.list";
    private static final int NOTIFY_TIME = 2;

    @Override
    protected void initData() {

        registEventBus();

        noDataIv.setImageResource(R.mipmap.img_no_course_wait);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == NOTIFY_TIME){
                    if(!Validators.isEmpty(courseList)){
                        courseWaitAdapter.notifyData();
                    }
                }
                super.handleMessage(msg);
            }
        };
        timeRunnable = new TimeRunnable();
        timeThread = new Thread(timeRunnable);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recycleView.setLayoutManager(linearLayoutManager);
        courseWaitAdapter = new CourseWaitAdapter(getActivity(), courseList);
        recycleView.setAdapter(courseWaitAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getOrderList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();

    }

    @Subscribe
    public void onEvent(String flag) {
        if (flag.equals(REFRESH_COURSE_WAIT_LIST)) {
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
//        handler.removeCallbacks(timeRunnable);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_course_list;
    }

    /**
     * 计时线程
     */
    class TimeRunnable implements Runnable {
        final String finalTime = getString(R.string.final_time);
        boolean endThread;

        @Override
        public void run() {

            while (!endThread) {
                try {

                    Thread.sleep(1000);

                    for (OrderResult.Order order : courseList) {
                        boolean isUpTime = true;
                        if (order.getOrderStatus() == 1) {
                            isUpTime = false;
                        } else if (order.getOrderStatus() == 5) {
                            isUpTime = true;
                        }

                        int time = 0;

                        if (isUpTime) {
                            time = (int) ((new Date().getTime() - order.getAnswerTime()) / 1000);
                        } else {
                            time = (int) ((order.getAnswerTime() - new Date().getTime()) / 1000);
                        }
                        String timeFormat;
                        String hh = new DecimalFormat("00").format(time / 3600);
                        String mm = new DecimalFormat("00").format(time % 3600 / 60);
                        String ss = new DecimalFormat("00").format(time % 60);
                        timeFormat = new String(hh + ":" + mm + ":" + ss);
                        if (time < 0) {
                            timeFormat = finalTime;
                        }
                        order.setChangeTime(timeFormat);
                    }

                    Message msg = new Message();
                    msg.what = NOTIFY_TIME;
                    handler.sendMessage(msg);
                } catch (Exception e) {

                }
            }
        }
    }

    /**
     * 获取订单列表
     */
    private void getOrderList() {

        Map<String, String> map = new HashMap<>();
        map.put("studentId", SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getWaitingOrderList(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderResult>(getActivity()) {
            @Override
            protected void _onNext(OrderResult orderResult) {
                courseList.clear();
                courseList.addAll(orderResult.getOrderList());
                courseWaitAdapter.notifyDataSetChanged();

                refreshLayout.finishRefresh();
//                handler.post(timeRunnable);
                if (!Validators.isEmpty(courseList)){
                    if (!timeThread.isAlive()){
                        timeThread.start();
                    }
                    noDataIv.setVisibility(View.GONE);
                }else{
                    noDataIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
                if (null != refreshLayout){
                    refreshLayout.finishRefresh();
                }
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }
}
